package pub.guoxin.oops.manager.endpoint;


import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import pub.guoxin.oops.constants.OopsPathConstants;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;

/**
 * Created by guoxin on 18-1-24.
 */
@Slf4j
//@Component
//@ServerEndpoint(OopsPathConstants.DEVICE_PATH + "/{username}")
public class ChatRoomServerEndpoint {

    private static Map<String, Session> livingSessions = Maps.newConcurrentMap();

    @OnOpen
    public void openSession(@PathParam("username") String username, Session session) {
        String sessionId = session.getId();
        livingSessions.put(sessionId, session);
        log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    }

    @OnMessage
    public void onMessage(@PathParam("username") String username, Session session, String message) {
        sendTextAll("用户[" + username + "] : " + message);
    }

    private void sendTextAll(String message) {
        livingSessions.forEach((sessionId, session) -> sendText(session, message));
    }

    @OnClose
    public void onClose(@PathParam("username") String username, Session session) {
        String sessionId = session.getId();
        // 当前的Session 移除
        livingSessions.remove(sessionId);
        // 并且通知其他人当前用户已经离开聊天室了
        sendTextAll("用户[" + username + "] 已经离开聊天室了！");
    }


    private void sendText(Session session, String message) {
        RemoteEndpoint.Basic basic = session.getBasicRemote();
        try {
            basic.sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}